<template>
    <a-modal v-if="state.open"  v-model:open="state.open" title="组织成员选择" width="820px" @ok="handleOk"
        @cancel="handleClose" >
        <a-card>
            <div class="select-dept-role-user-container flex justify-between">
                <div class="left flex-1 p-2">
                    <a-tabs v-model:activeKey="state.activeKey" @change="handleTabChange">
                        <a-tab-pane key="dept" tab="部门" >
                            <dept ref="deptRef" :dept-data="state.deptData" @change="onDeptChange" v-if="props.isShowDept"/>
                        </a-tab-pane>
                        <a-tab-pane key="role" tab="角色" >
                            <role ref="roleRef" :role-data="state.roleData" @change="onRoleChange" v-if="props.isShowRole"/>
                        </a-tab-pane>
                        <a-tab-pane key="user" tab="用户" >
                            <user ref="userRef" :org-user-data="state.deptData" @change="onUserChange" v-if="props.isShowUser"/>
                        </a-tab-pane>
                    </a-tabs>
                </div>
                <div class="right flex-1 p-2">
                    <div v-if="state.showList.length > 0">
                        <a-list item-layout="horizontal" :data-source="state.showList">
                            <template #renderItem="{ item }">
                                <a-list-item>
                                    <a-list-item-meta>
                                        <template #title>
                                            <div class="selected-item">
                                                <span>
                                                    {{ item.name }}
                                                </span>
                                                <DeleteOutlined @click="deleteSelected(item)" />
                                            </div>
                                        </template>
                                    </a-list-item-meta>
                                </a-list-item>
                            </template>
                        </a-list>
                    </div>
                    <a-empty v-else />
                </div>
            </div>
        </a-card>
    </a-modal>
</template>

<script setup lang="ts">
import { apiSysOrgGetDeptUsers } from '@/api/sys/sysOrg';
import { apiSysRolePagePost } from '@/api/sys/sysRole';
import type { ResType } from '@/api/types';
import type { TreeProps } from 'ant-design-vue';
import { nextTick, onBeforeMount, reactive, ref, useTemplateRef, watch } from 'vue';
import dept from './dept.vue';
import role from './role.vue';
import user from './user.vue';

const props = withDefaults(defineProps<{
    isShowDept?:boolean
    isShowRole?:boolean
    isShowUser?:boolean
}>(),{
    isShowDept:true,
    isShowRole:true,
    isShowUser:true
})

const emits = defineEmits<{
    (e: 'selected', data: any): void
}>()

const deptRef = useTemplateRef('deptRef')
const roleRef = useTemplateRef('roleRef')
const userRef = useTemplateRef('userRef')

let oldSelectedRoles: any[] = []
let oldSelectedDepts: any[] = []
let oldSelectedUsers: any[] = []

const state = reactive<any>({
    open: false,
    activeKey: 'dept',
    deptSearchVal: "",
    roleSearchVal: "",
    userSearchVal: "",
    expandedKeys: [],
    selectedKeys: [],
    checkedKeys: [],
    deptData: [],
    autoExpandParent: true,
    roleData: [],
    roleDataTemp: [], //副本
    showList: []
})


const handleOk = () => {
    handleClose()
    emits('selected', state.showList)
}

const handleClose = () => {
    state.open = false
    state.activeKey = 'dept'
}

const handleOpen = async (val?: any) => {
    state.showList = val || []
    state.open = true

    const dept: any[] = []
    const role: any[] = []
    const user: any[] = []
    state.showList.forEach((item: any) => {
        if (item.type == 'dept') {
            dept.push(item)
        } else if (item.type == 'role') {
            role.push(item)
        } else if (item.type == 'user') {
            user.push(item)
        }
    })
    oldSelectedDepts = dept
    oldSelectedRoles = role
    oldSelectedUsers = user
    nextTick(()=>{
        setCheckedByType()
    })
}

const setCheckedByType = () => {
    const dept: any[] = []
    const role: any[] = []
    const user: any[] = []
    state.showList.forEach((item: any) => {
        if (item.type == 'dept') {
            dept.push(item)
        } else if (item.type == 'role') {
            role.push(item)
        } else if (item.type == 'user') {
            user.push(item)
        }
    })
    nextTick(()=>{
        dept.length > 0 && deptRef.value?.setCheckedKeys(dept.map((i: any) => i.id))
        role.length > 0 && roleRef.value?.setCheckedKeys(role.map((i: any) => i.id))
    
        if (user.length > 0) {
            let keys = user.map((i: any) => i.id)
            const setCheckedKeys = (keys: any[]) => {
                function _map(data: any[]) {
                    for (let i = 0; i < data.length; i++) {
                        const item = data[i];
                        if (item.users.length > 0) {
                            item.users.forEach((i: any) => {
                                if (keys.includes(i.id)) {
                                    i.checked = true
                                }
                            })
                        }
                        if (Array.isArray(item.children)) {
                            _map(item.children)
                        }
                    }
                }
                _map(state.deptData)
            }
            setCheckedKeys(keys)
        }
    })
}

// 激活已选
const handleTabChange = (key:string)=>{
    setCheckedByType()
}


const baseFilter = (oldData: any[]) => {
    state.showList = state.showList.filter((item: any) => {
        if (oldData.findIndex((i: any) => i.id == item.id) == -1) {
            return item
        }
    })
}

const onDeptChange = (data: any[]) => {
    console.log("dept",data);
    baseFilter(oldSelectedDepts)
    state.showList.push(...data)
    oldSelectedDepts = data
}


const onRoleChange = (data: any[]) => {
    console.log("role",data);
    baseFilter(oldSelectedRoles)
    state.showList.push(...data)
    oldSelectedRoles = data
}


const onUserChange = (data: any[]) => {
    console.log("user",data);
    baseFilter(oldSelectedUsers)
    state.showList.push(...data)
    oldSelectedUsers = data
}
const init = async () => {
    apiSysOrgGetDeptUsers().then((res: ResType<any[]>) => {
        state.deptData = res.data.result
        
    })
    apiSysRolePagePost({ page: 1, pageSize: 50, total: 0 }).then((res: any) => {
        state.roleData = res.data.result.items
    })
}

onBeforeMount(()=>{
    init()
})

const deleteSelected = (item: any) => {
    // const index = state.showList.findIndex((i:any)=>i.id == item.id)
    // state.showList.splice(index,1)
    // state.roleData.forEach((i:any)=>{
    //     if(i.id == item.id){
    //         i.checked = false
    //     }
    // })
}

defineExpose({
    handleOpen
})
</script>

<style lang='scss' scoped>
:deep(.ant-card-body) {
    padding: 0;
    overflow: hidden;
}

.select-dept-role-user-container {
    .left {
        border-right: 1px solid #f0f0f0;
        height: 450px;
        overflow: hidden;
        overflow-y: auto;
        scrollbar-gutter: stable;

        &::-webkit-scrollbar {
            width: 6px;
            background: transparent;
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:hover::-webkit-scrollbar {
            opacity: 1;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-thumb,
        &::-webkit-scrollbar-track {
            border-radius: 4px;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-track {
            background-color: transparent;
        }

        &::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        &:hover::-webkit-scrollbar-thumb {
            background-color: #a19e9e;

            &:hover {
                background-color: #ccc;
            }
        }
    }

    .right {
        height: 450px;
        overflow: hidden;
        overflow-y: auto;
        scrollbar-gutter: stable;

        .selected-item {
            width: 100%;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 2px 4px;
            cursor: pointer;
        }

        &::-webkit-scrollbar {
            width: 6px;
            background: transparent;
            opacity: 0;
            transition: opacity 0.3s;
        }

        &:hover::-webkit-scrollbar {
            opacity: 1;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-thumb,
        &::-webkit-scrollbar-track {
            border-radius: 4px;
        }

        &::-webkit-scrollbar-corner,
        &::-webkit-scrollbar-track {
            background-color: transparent;
        }

        &::-webkit-scrollbar-thumb {
            background-color: transparent;
        }

        &:hover::-webkit-scrollbar-thumb {
            background-color: #a19e9e;

            &:hover {
                background-color: #ccc;
            }
        }
    }
}

:deep(.ant-list-item-meta-content) {
    transition: all 0.3s;

    &:hover {
        background-color: #f0f8ff;
    }
}
</style>